<template>
  <basic-container>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button
          type="primary"
          size="small"
          icon="el-icon-sort"
          plain
          @click="handleRateAdjust"
          >费率调整
        </el-button>
        <!-- <el-button
          type="danger"
          size="small"
          icon="el-icon-delete"
          plain
          v-if="permission.oem_policy_delete"
          @click="handleDelete"
          >删 除
        </el-button> -->
      </template>
      <!-- <template slot="menuRight">
        <el-button
          type="success"
          size="small"
          plain
          icon="el-icon-upload2"
          v-if="permission.oem_policy_import"
          @click="handleImport"
          >导入
        </el-button>
        <el-button
          type="warning"
          size="small"
          plain
          icon="el-icon-download"
          v-if="permission.oem_policy_export"
          @click="handleExport"
          >导出
        </el-button>
      </template> -->
    </avue-crud>
    <el-dialog
      title="费率调整"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="dialogRateVisible"
      :before-close="handleClose"
    >
      <avue-form ref="rateForm" :option="rateOption" v-model="rateForm" @submit="rateSubmit"></avue-form>
    </el-dialog>
    <el-dialog
      title="数据导入"
      append-to-body
      :visible.sync="excelBox"
      width="555px"
    >
      <avue-form
        :option="excelOption"
        v-model="excelForm"
        :upload-after="uploadAfter"
      >
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getList,
  getDetail,
  add,
  update,
  remove,
  adjustRate,
} from "@/api/rb-oem/oempolicy/oem_policy";
// import { getList as getAisleList } from "@/api/rb-oem/aisle/pay_aisle";
import { getAisleOemList } from "@/api/rb-oem/serviceinfo/service_info";
import { mapGetters } from "vuex";
import { getToken } from "@/util/auth";
export default {
  data() {
    const validateRate = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入费率'));
      } else {
        callback();
      }
    };
    return {
      form: {},
      query: {},
      search: {},
      loading: true,
      dialogRateVisible: false,
      excelBox: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        height: "calc(50vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        menu: false,
        viewBtn: false,
        selection: true,
        searchMenuSpan: 6,
        columnBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        column: [
          {
            label: "通道编号",
            prop: "aisleCode",
            type: "input",
            search: true,
            overHidden: true,
          },
          {
            label: "通道名称",
            prop: "aisleName",
            type: "input",
            search: true,
            overHidden: true,
          },
          {
            label: "租户名称",
            prop: "tenantName",
            type: "input",
            hide: true,
            overHidden: true,
          },
          {
            label: "用户名称",
            prop: "userName",
            type: "input",
            search: true,
            overHidden: true,
          },
          {
            label: "政策编号",
            prop: "polNo",
            type: "input",
            search: true,
            overHidden: true,
          },
          {
            label: "政策名称",
            prop: "polName",
            type: "input",
            width: 270,
            search: true,
            overHidden: true,
          },
          {
            label: "政策分类",
            prop: "polKindName",
            display: false,
            overHidden: true,
          },
          {
            label: "政策分类",
            prop: "polKind",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=pol_kind",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            dataType: "string",
            search: true,
            hide: true,
            overHidden: true,
          },
          // {
          //   label: "政策类型",
          //   prop: "polTypeName",
          //   display: false,
          // },
          // {
          //   label: "政策类型",
          //   prop: "polType",
          //   type: "select",
          //   dicUrl: "/api/blade-system/dict/dictionary?code=pol_type",
          //   props: {
          //     label: "dictValue",
          //     value: "dictKey"
          //   },
          //   dataType: "string",
          //   sortable: true,
          //   search: true,
          //   hide: true
          // },
          {
            label: "政策类别",
            prop: "polCategoryName",
            display: false,
            overHidden: true,
          },
          {
            label: "政策类别",
            prop: "polCategory",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=pol_category",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            dataType: "string",
            sortable: true,
            search: true,
            hide: true,
            overHidden: true,
          },
          
        ],
      },
      data: [],
      rateForm: {
        adjustType: "",
        type: "",
        aisleCodeList: [],
        rate: "",
      },
      rateRules: {
        adjustType: [
          { required: true, message: "请选择费率类型", trigger: "blur" },
        ],
        type: [
          { required: true, message: "请选择调整类型", trigger: "blur" },
        ],
        aisleCodeList: [
          { required: true, message: "请选择通道", trigger: "blur" },
        ],
        rate: [
          { required: true, message: "请输入费率", trigger: "blur" },
        ],
      },
      rateOption: {
        column: [
          {
            label: "费率类型",
            prop: "adjustType",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=adjust_type",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            dataType: "string",
            span: 12,
            hide: true,
            rules: [{
              required: true,
              message: "请选择费率类型",
              trigger: "blur"
            }]
          },
          {
            label: "调整类型",
            prop: "type",
            type: "radio",
            dicData: [{
                label: '上调',
                value: 1
            }, {
                label: '下调',
                value: 2
            }],
            dataType: "string",
            span: 12,
            hide: true,
            rules: [{
              required: true,
              message: "请选择调整类型",
              trigger: "blur"
            }]
          },
          {
            label: "通道",
            prop: "aisleCodeList",
            type: "tree",
            props: {
              label: "aisleName",
              value: "aisleCode"
            },
            dicData: [],
            // dataType: "string",
            filterText: '搜索通道',
            multiple:true,
            span: 12,
            hide: true,
            rules: [{
              required: true,
              message: "请选择通道",
              trigger: "blur"
            }]
          },
          {
            label: "费率",
            prop: "rate",
            type: 'number',
            precision: 4,
            step: 0.0001,
            mock:{
              type:'number',
              max: 1,
              min: 2,
              precision: 4
            },
            minRows: 0,
            maxRows: 1,
            row: true,
            span: 12,
            rules: [{
              required: true,
              trigger: "blur",
              validator: validateRate
            }]
          },
        ],
      },
      adjustTypeList: [],
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data",
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/rb-oem/oem/oempolicy/oem_policy/import",
          },
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24,
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.oem_policy_add, false),
        viewBtn: this.vaildData(this.permission.oem_policy_view, false),
        delBtn: this.vaildData(this.permission.oem_policy_delete, false),
        editBtn: this.vaildData(this.permission.oem_policy_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  methods: {
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    /* 费率提交 */
    rateSubmit(row, done, loading) {
      adjustRate(row).then(
        () => {
          this.onLoad(this.page);
          this.dialogRateVisible = false;
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.rateForm.resetForm();
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    /* 政策费率整体上下调 回显 */
    handleRateAdjust() {
      this.dialogRateVisible = true;
      getAisleOemList(
        '-1',
        '-1',
      ).then((res) => {
        const column = this.findObject(this.rateOption.column, "aisleCodeList");
        column.dicData = res.data.data.records;
      });
    },
    handleClose(done) {
      this.onLoad(this.page);
      done();
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query),
        '0'
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    handleImport() {
      this.excelBox = true;
    },
    handleExport() {
      let exQuery = ``;
      exQuery += `&polNo=${this.search.polNo}`;
      exQuery += `&polName=${this.search.polName}`;
      exQuery += `&polKind=${this.search.polKind}`;
      exQuery += `&polType=${this.search.polType}`;
      exQuery += `&polCategory=${this.search.polCategory}`;
      exQuery += `&aisleCode=${this.search.aisleCode}`;
      exQuery += `&isTemplate=${this.search.isTemplate}`;
      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        window.open(
          `/api/rb-oem/oem/oempolicy/oem_policy/export?${
            this.website.tokenHeader
          }=${getToken()}` + exQuery
        );
      });
    },
    handleTemplate() {
      window.open(
        `/api/rb-oem/oem/oempolicy/oem_policy/export-template?${
          this.website.tokenHeader
        }=${getToken()}`
      );
    },
    uploadAfter(res, done) {
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    },
  },
};
</script>

<style lang="scss" scoped>
.pay-company-box {
  width: 100%;
  height: 100%;
  display: flex;
  align-content: flex-start;
  flex-flow: row wrap;
  align-items: center;
  &.pay-justify-content {
    justify-content: center;
  }
  .pay-company-item {
    width: 200px;
  }
  span {
    display: inline-block;
    margin-right: 6px;
  }
}
</style>
